package com.zhaoyue.study.concurrency.thread;

import javafx.scene.layout.Priority;

/**
 * Created with IntelliJ IDEA.
 * User: zhaoyue
 * Date: 2016/8/30
 * Time: 16:02
 * 获取和设置线程信息
 */
public class Calculator implements Runnable{

    private int number;
    public Calculator(int number){
        this.number = number;
    }

    public void run() {
        for(int i=1;i<=10;i++){
            System.out.printf("%s: %d * %d = %d\n", Thread.currentThread().getName(), number, i, i * number);
        }
    }

    private static void writeThreadInfo(Thread thread, Thread.State state) {
        System.out.printf("Main : Id %d - %s\n",thread.getId(),thread.getName());//线程Id和线程状态
        System.out.printf("Main : Priority: %d\n",thread.getPriority());//优先级
        System.out.printf("Main : Old State: %s\n",state);//状态
        System.out.printf("Main : New State: %s\n",thread.getState());//获取线程状态
        System.out.printf("Main : ************************************\n");
    }


    public static void main(String[] args) {
        Thread[] threads = new Thread[10];
        Thread.State status[] = new Thread.State[10];

        for(int i=0;i<10;i++){
            threads[i] = new Thread(new Calculator(i));
            if(i%2==0){
                threads[i].setPriority(Thread.MAX_PRIORITY);
            }else {
                threads[i].setPriority(Thread.MIN_PRIORITY);
            }
            threads[i].setName("Thread " + i);
        }

        for(int i=0;i<10;i++){
            threads[i].start();
        }

        boolean finish=false;
        while (!finish) {
            for (int i=0; i<10; i++){
                if (threads[i].getState()!=status[i]) {
                    writeThreadInfo(threads[i],status[i]);
                    status[i]=threads[i].getState();
                }
            }

            finish=true;
            for (int i=0; i<10; i++){
                finish=finish && (threads[i].getState()== Thread.State.TERMINATED);
            }
        }


    }
}
